package com.anfeng.cms.api.org;

import com.anfeng.cms.api.support.ConstEum;
import com.anfeng.cms.api.support.ResDto;
import com.anfeng.cms.common.Common;
import com.anfeng.cms.domain.org.AfDepartment;
import com.anfeng.cms.domain.org.AfJob;
import com.anfeng.cms.domain.org.AfPost;
import com.anfeng.cms.service.emp.IAfEmployeeInfoService;
import com.anfeng.cms.service.impl.ExcelSupport;
import com.anfeng.cms.service.org.IAfDepartmentService;
import com.anfeng.cms.service.org.IAfJobService;
import com.anfeng.cms.service.org.IAfPostService;
import com.anfeng.cms.util.IdGeneratorUtil;
import com.anfeng.cms.util.JsonMapper;
import com.anfeng.cms.util.base.POIUtil;
import com.baomidou.mybatisplus.plugins.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 吴朋
 * @date 2019/7/23
 */
@RestController
@Slf4j
@RequestMapping(value = "/api/org", name = "部门管理")
public class OrgEndPoint {

    @Autowired
    private IAfDepartmentService departmentService;
    @Autowired
    private IAfEmployeeInfoService employeeInfoService;
    @Autowired
    private IAfPostService postService;
    @Autowired
    private IAfJobService jobService;
    @Autowired
    private ExcelSupport excelSupport;

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    @ResponseBody
    public ResDto addDepartment(String parentId, String name) {
        if (StringUtils.isBlank(parentId) || StringUtils.isBlank(name)) {
            log.error("新增部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 判断是否是顶级的
        if (parentId.equals("0")) {
            parentId = null;
        }
        // 根据上级id 和 部门名称 判断是否存在
        AfDepartment departmentInfo = departmentService.getDepartmentInfo(parentId, name);
        if (null != departmentInfo) {
            log.error("新增部门已存在 {}", JsonMapper.defaultMapper().toJson(departmentInfo));
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        String deptId = departmentService.addDepartment(parentId, name);
        if (StringUtils.isBlank(deptId)) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增部门信息失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/dept/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResDto editDepartment(String deptId, String name) {
        if (StringUtils.isBlank(deptId) || StringUtils.isBlank(name)) {
            log.error("修改部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据部门id 获取部门信息 进行对比
        AfDepartment departmentInfo = departmentService.getDepartmentInfo(deptId);
        if (null == departmentInfo) {
            log.error("根据部门id 未查询到相关部门信息 {}", deptId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        if (name.equals(departmentInfo.getName())) {
            return new ResDto(ConstEum.SUCCESS);
        }
        // 获取上级部门名字
        AfDepartment parentDept = departmentService.getDepartmentInfo(departmentInfo.getParentId());
        String parentMark = "";
        if (parentDept != null) {
            parentMark = parentDept.getRemark();
        }
        departmentInfo.setName(name);
        departmentInfo.setRemark(parentMark+"/" + name);
        departmentInfo.setModifiedTime(new Date());
        boolean update = departmentService.updateById(departmentInfo);
        if (!update) {
            log.error("修改部门信息失败 {}", JsonMapper.defaultMapper().toJson(departmentInfo));
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("修改部门信息失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/dept/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResDto deleteDepartment(String deptId) {
        if (StringUtils.isBlank(deptId)) {
            log.error("删除部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据部门id 获取部门信息 进行对比
        AfDepartment departmentInfo = departmentService.getDepartmentInfo(deptId);
        if (null == departmentInfo) {
            log.error("根据部门id 未查询到相关部门信息 {}", deptId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 获取部门下是否还有员工
        int count = employeeInfoService.getDepartmentEmployeeCount(departmentInfo.getId());
        if (count > 0) {
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setMsg("部门下存在员工部门删除");
            return resDto;
        }
        //departmentInfo.setState(Common.DATA_STATE_DELETE);
        //departmentInfo.setModifiedTime(new Date());
        //boolean update = departmentService.updateById(departmentInfo);
        //if (!update) {
        //    ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
        //    resDto.setMsg("删除部门失败");
        //    return resDto;
        //}
        // 将部门即子部门删除
        int update = departmentService.deleteDepartmentAndSub(departmentInfo.getId());
        if (update == Common.RETURN_FAILED) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("删除部门失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/dept/import", method = RequestMethod.POST)
    @ResponseBody
    public ResDto importDepartment(MultipartFile file) {
        ResDto resDto;
        if (file == null) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        //读取信息
        try {
            Map<String, Object> readExcelDepart = POIUtil.readExcelDepart(file.getBytes(), file.getOriginalFilename());
            if (null == readExcelDepart || readExcelDepart.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfDepartment> departmentList = (List<AfDepartment>) readExcelDepart.get("departments");
            if (null == departmentList || departmentList.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfDepartment> insertErrorInfo = new ArrayList<>();
            for (AfDepartment info : departmentList) {
                int insert = departmentService.addDepartmentByRemark(info.getRemark());
                if (insert == Common.DATA_STATE_DELETE) {
                    log.error("导入部门信息失败 {}", info.getRemark());
                    insertErrorInfo.add(info);
                }
            }
            if (!insertErrorInfo.isEmpty()) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("导入失败");
                return resDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/dept/download/template", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadDeptTemplete(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        excelSupport.downLoadTemplete(httpServletRequest, httpServletResponse, "department.xls");
    }

    @RequestMapping(value = "/post/info", method = RequestMethod.GET)
    @ResponseBody
    public ResDto getPostInfo(String name) {
        ResDto resDto;
        List<AfPost> datasInfo = new ArrayList<>();
        if (StringUtils.isBlank(name)) {
            List<AfPost> allPosts = postService.getAllPosts();
            if (allPosts != null && !allPosts.isEmpty()) {
                datasInfo.addAll(allPosts);
            }
        } else {
            // 根据岗位名称 查看是否存在
            AfPost post = postService.getPostByName(name);
            if (post != null) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("已存在该岗位");
                return resDto;
            } else {
                datasInfo.add(post);
            }
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(datasInfo));
        return resDto;
    }

    @RequestMapping(value = "/post/add", method = RequestMethod.POST)
    @ResponseBody
    public ResDto addPost(String name) {
        if (StringUtils.isBlank(name)) {
            log.error("新增部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据岗位名称 查看是否存在
        AfPost post = postService.getPostByName(name);
        if (post != null) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("已存在该岗位");
            return resDto;
        }
        String pid = postService.addPost(name);
        if (StringUtils.isBlank(pid)) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增岗位失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/post/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResDto editPost(String postId, String name) {
        if (StringUtils.isBlank(postId) || StringUtils.isBlank(name)) {
            log.error("修改岗位信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        AfPost afPost = postService.getPostById(postId);
        if (afPost == null) {
            log.error("修改岗位信息 失败 传入参数有误 {}", postId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        afPost.setName(name);
        afPost.setModifiedTime(new Date());
        boolean update = postService.updateById(afPost);
        if (!update) {
            log.error("更新岗位信息失败 {}", JsonMapper.defaultMapper().toJson(afPost));
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/post/state", method = RequestMethod.POST)
    @ResponseBody
    public ResDto forbidPost(String postId, Integer state) {
        if (StringUtils.isBlank(postId) || null == state || (state != Common.DATA_STATE_DELETE && state != Common.DATA_STATE_NORMAL)) {
            log.error("删除部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        AfPost afPost = postService.selectById(postId);
        if (afPost == null) {
            log.error("未查询到相关工种信息 {}", postId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        if (state.equals(afPost.getState())) {
            return new ResDto(ConstEum.SUCCESS);
        }
        afPost.setState(state);
        afPost.setModifiedTime(new Date());
        boolean update = postService.updateById(afPost);
        if (!update) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("禁止");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/post/import", method = RequestMethod.POST)
    @ResponseBody
    public ResDto importPosts(MultipartFile file) {
        ResDto resDto;
        if (file == null) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        //读取信息
        try {
            Map<String, Object> readExcelPost = POIUtil.readExcelPost(file.getBytes(), file.getOriginalFilename());
            if (null == readExcelPost || readExcelPost.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfPost> postList = (List<AfPost>) readExcelPost.get("posts");
            if (null == postList || postList.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfPost> insertErrorInfo = new ArrayList<>();
            for (AfPost info : postList) {
                String insert = postService.addPost(info.getName());
                if (StringUtils.isBlank(insert)) {
                    log.error("导入岗位信息失败 {}", info.getName());
                    insertErrorInfo.add(info);
                }
            }
            if (!insertErrorInfo.isEmpty()) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("导入失败");
                return resDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/post/download/template", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadPostTemplete(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        excelSupport.downLoadTemplete(httpServletRequest, httpServletResponse, "post.xls");
    }

    @RequestMapping(value = "/job/info", method = RequestMethod.GET)
    @ResponseBody
    public ResDto getJobInfo(String name) {
        ResDto resDto;
        List<AfJob> datasInfo = new ArrayList<>();
        if (StringUtils.isBlank(name)) {
            List<AfJob> allJobs = jobService.getAllJobs();
            if (allJobs != null && !allJobs.isEmpty()) {
                datasInfo.addAll(allJobs);
            }
        } else {
            // 根据工种名称 查看是否存在
            AfJob job = jobService.getJobByName(name);
            if (job != null) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("已存在该工种");
                return resDto;
            } else {
                datasInfo.add(job);
            }
        }
        resDto = new ResDto(ConstEum.SUCCESS);
        resDto.setDatas(JsonMapper.defaultMapper().toJson(datasInfo));
        return resDto;
    }

    @RequestMapping(value = "/job/add", method = RequestMethod.POST)
    @ResponseBody
    public ResDto addJob(String name) {
        if (StringUtils.isBlank(name)) {
            log.error("新增工种信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        // 根据岗位名称 查看是否存在
        AfJob job = jobService.getJobByName(name);
        if (job != null) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("已存在该工种");
            return resDto;
        }
        String jid = jobService.addJob(name);
        if (StringUtils.isBlank(jid)) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("新增工种失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/job/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResDto editJob(String jobId, String name) {
        if (StringUtils.isBlank(jobId) || StringUtils.isBlank(name)) {
            log.error("修改工种信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        AfJob afJob = jobService.getJobById(jobId);
        if (afJob == null) {
            log.error("修改工种信息 失败 传入参数有误 {}", jobId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        afJob.setName(name);
        afJob.setModifiedTime(new Date());
        boolean update = jobService.updateById(afJob);
        if (!update) {
            log.error("更新工种信息失败 {}", JsonMapper.defaultMapper().toJson(afJob));
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("更新失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/job/state", method = RequestMethod.POST)
    @ResponseBody
    public ResDto forbidJob(String postId, Integer state) {
        if (StringUtils.isBlank(postId) || null == state || (state != Common.DATA_STATE_DELETE && state != Common.DATA_STATE_NORMAL)) {
            log.error("删除部门信息失败 传入参数为空");
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        AfPost afPost = postService.selectById(postId);
        if (afPost == null) {
            log.error("未查询到相关工种信息 {}", postId);
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        if (state.equals(afPost.getState())) {
            return new ResDto(ConstEum.SUCCESS);
        }
        afPost.setState(state);
        afPost.setModifiedTime(new Date());
        boolean update = postService.updateById(afPost);
        if (!update) {
            ResDto resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("禁止");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/job/import", method = RequestMethod.POST)
    @ResponseBody
    public ResDto importJobs(MultipartFile file) {
        ResDto resDto;
        if (file == null) {
            return new ResDto(ConstEum.PARAM_ERROR);
        }
        //读取信息
        try {
            Map<String, Object> readExcelJob = POIUtil.readExcelJob(file.getBytes(), file.getOriginalFilename());
            if (null == readExcelJob || readExcelJob.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfJob> jobList = (List<AfJob>) readExcelJob.get("jobs");
            if (null == jobList || jobList.isEmpty()) {
                return new ResDto(ConstEum.PARAM_ERROR);
            }
            List<AfJob> insertErrorInfo = new ArrayList<>();
            for (AfJob info : jobList) {
                String insert = jobService.addJob(info.getName());
                if (StringUtils.isBlank(insert)) {
                    log.error("导入工种信息失败 {}", info.getName());
                    insertErrorInfo.add(info);
                }
            }
            if (!insertErrorInfo.isEmpty()) {
                resDto = new ResDto(ConstEum.SERVER_ERROR);
                resDto.setMsg("导入失败");
                return resDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg("导入失败");
            return resDto;
        }
        return new ResDto(ConstEum.SUCCESS);
    }

    @RequestMapping(value = "/job/download/template", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadJobTemplete(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        excelSupport.downLoadTemplete(httpServletRequest, httpServletResponse, "job.xls");
    }
}
